package com.h2o3.carmack.network;

import java.io.IOException;

import org.glassfish.grizzly.http.server.HttpServer;
import org.glassfish.grizzly.http.server.NetworkListener;
import org.glassfish.grizzly.websockets.WebSocketAddOn;
import org.glassfish.grizzly.websockets.WebSocketApplication;
import org.glassfish.grizzly.websockets.WebSocketEngine;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationListener;
import org.springframework.context.event.ContextStartedEvent;

/**
 * @author chensheng
 * @version $Id: CarmackServer.java, v 0.1 1/18/14 8:25 PM chensheng Exp $
 */
public class CarmackServer implements InitializingBean, ApplicationListener<ContextStartedEvent> {
    private HttpServer           httpServer;

    private int                  port;
    private String               path;
    private WebSocketApplication webSocketApplication;

    @Override
    public void afterPropertiesSet() throws Exception {
        httpServer = HttpServer.createSimpleServer(null, port);
        final WebSocketAddOn webSocketAddOn = new WebSocketAddOn();
        for (NetworkListener listener : httpServer.getListeners()) {
            listener.registerAddOn(webSocketAddOn);
        }

        WebSocketEngine.getEngine().register("", path, webSocketApplication);
    }

    @Override
    public void onApplicationEvent(ContextStartedEvent contextRefreshedEvent) {
        synchronized (this) {
            try {
                if (!httpServer.isStarted()) {
                    httpServer.start();
                }
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public String getPath() {
        return path;
    }

    public void setPath(String path) {
        this.path = path;
    }

    public WebSocketApplication getWebSocketApplication() {
        return webSocketApplication;
    }

    public void setWebSocketApplication(WebSocketApplication webSocketApplication) {
        this.webSocketApplication = webSocketApplication;
    }
}
